<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Magic
 * Date: 11-5-8
 * Time: 下午8:17
 * To change this template use File | Settings | File Templates.
 */

class File_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();

        $this->file_path = realpath(APPPATH . '../user_file');

    }

    /**
     * @param  $uploader name of the uploader
     * @return Infomation about the uploaded files.
     */
    public function do_upload($keywords, $permission, $file_type_allowed, $file_type, $overwrite = FALSE, $isUpdate = FALSE, $file_id = 0)
    {
        $config = array(
            'upload_path' => $this->file_path,
            'overwrite' => $overwrite,
            'allowed_types' => $file_type_allowed,
            'max_size' => '0'
        );

        $this->load->library('upload', $config);
        $this->upload->do_upload();

        $file_info = $this->upload->data();
        $file_name = $file_info['file_name'];
        $file_dir = base_url() . 'user_file/' . $file_info['file_name'];


        $content = '';
        $url = './user_file/' . $file_info['file_name'];
        $fp = fopen($url, 'r');
        if (!$fp) {
            die('Filed to load file.');
        }
        while (!feof($fp))
        {
            $content = $content . fgets($fp);
        }
        fclose($fp);

        $autokeys = $this->filter($content);

        $username = $this->session->userdata('username');

        if (empty($file_name)) die('Please select a file.');
        if ($isUpdate == TRUE) {
            if ($file_type == 0) {
                $sql = "UPDATE file_info
                        SET `file_name` = '$file_name',
                            `file_dir` = '$file_dir',
                            `file_keyword` = $keywords,
                            `file_visted` = 0,
                            `file_permission` = '$permission',
                            `file_keyword_auto` = '$autokeys'
                        WHERE `file_id` = '$file_id'
                        LIMIT 1";
            } else {
                $sql = "UPDATE image_info
                        SET `name` = '$file_name',
                            `dir` = '$file_dir',
                            `visted` = 0
                        WHERE `file_id` = '$file_id'
                        LIMIT 1";
            }

            return $this->db->query($sql);
        } else {
            if ($file_type == 0) {
                $new_file_insert_data = array(
                    'file_name' => $file_name,
                    'file_dir' => $file_dir,
                    'file_owner_username' => $username,
                    'file_keyword' => $keywords,
                    'file_permission' => $permission,
                    'file_keyword_auto' => $autokeys
                );
                $insert = $this->db->insert('file_info', $new_file_insert_data);
            } else {
                $new_file_insert_data = array(
                    'name' => $file_name,
                    'dir' => $file_dir,
                    'owner' => $this->session->userdata('username')
                );
                $insert = $this->db->insert('image_info', $new_file_insert_data);
            }
            return $insert;
        }
    }

    public function approve_file($id, $type)
    {
        if ($type == '1') {
            $this->db->query("UPDATE `file_info` SET `file_approved` = 1 WHERE `file_id` = '$id' LIMIT 1");
        } else {
            $this->db->query("UPDATE `image_info` SET `approved` = 1 WHERE `id` = '$id' LIMIT 1");
        }

        if ($this->db->affected_rows()) {
            return true;
        } else {
            return false;
        }
    }

    public function remove_file($id, $type)
    {
        if ($type == '1') {
            $this->db->query("DELETE FROM `file_info` WHERE `file_id`= '$id' LIMIT 1;");
        } else {
            $this->db->query("DELETE FROM `image_info` WHERE `id`= '$id' LIMIT 1;");
        }

        if ($this->db->affected_rows()) {
            return true;
        } else {
            return false;
        }
    }

    public function filter($content)
    {
        $query = $this->db->query("SELECT `word` FROM `stopword`");
        foreach ($query->result() as $row) {
            if (preg_match("/$row->word/i", $content)) {
                $username = $this->session->userdata('username');
                $this->db->query("UPDATE `user_info` SET `point` = `point` - 0.2 WHERE `username` = '$username'");
                die('Your file contains stop words, -0.2 Points');
            }
        }

        $search = array(
            "'<script[^>]*?>.*?</script>'si",
            "'<style[^>]*?>.*?</style>'si",
            "'<[/!]*?[^<>]*?>'si",
            "'<!--[/!]*?[^<>]*?>'si",
            "'([rn])[s]+'",
            "'&(quot|#34);'i",
            "'&(amp|#38);'i",
            "'&(lt|#60);'i",
            "'&(gt|#62);'i",
            "'&(nbsp|#160);'i",
            "'&(iexcl|#161);'i",
            "'&(cent|#162);'i",
            "'&(pound|#163);'i",
            "'&(copy|#169);'i",
            "'&#(d+);'e");
        $replace = array(
            "",
            "",
            "",
            "",
            "\1",
            "\"",
            "&",
            "<",
            ">",
            " ",
            chr(161),
            chr(162),
            chr(163),
            chr(169),
            "chr(\1)");

        $out = preg_replace($search, $replace, $content);
        $words = str_word_count($out, 1);
        $result = array();
        foreach ($words as $w) {
            $lw = strtolower($w);
            $lw = str_replace("'", "", $lw);
            $lw = str_replace("-", "", $lw);
            //Stemming word
            $query = $this->db->query("SELECT * FROM `stemword` WHERE `word` =  '$lw'");
            if ($query->num_rows() > 0) {
                $row = $query->row();
                $isroot = $row->isroot;
                if (!$isroot) {
                    $lw = strtolower($row->belong);
                }
            }

            if (!(isset($result[$lw]))) {
                $result[$lw] = 1;
            } else {
                $result[$lw]++;
            }
        }
        arsort($result);
        $autokey = '';
        $max = (sizeof($result) >= 20) ? 20 : sizeof($result);
        $i = 0;
        foreach ($result as $r => $value) {
            $autokey = $autokey . ' ' . $r;
            if (($i++) > $max) {
                break;
            }
        }
        return $autokey;
    }
}
